package com.neusoft.EYSystem.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.neusoft.EYSystem.dao.UserDAO;
import com.neusoft.EYSystem.po.Client;
import com.neusoft.EYSystem.po.PageResponseBean;
import com.neusoft.EYSystem.po.ResponseBean;
import com.neusoft.EYSystem.po.User;
import com.neusoft.EYSystem.redisDao.RedisDAO;
import com.neusoft.EYSystem.service.UserService;
import com.neusoft.EYSystem.utils.JWTTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private RedisDAO redisDAO;

    @GetMapping("listAllName")
    public ResponseBean<List<String>> listAllUsernames() {
        ResponseBean<List<String>> response = new ResponseBean<>();
        try {
            List<User> users = userDAO.selectList(null);
            List<String> usernames = new ArrayList<>();
            if (users != null && !users.isEmpty()) {
                response.setStatus(200);
                response.setMsg("用户列表查询成功");
                for( User user : users) {
                    usernames.add(user.getUsername());
                }
                response.setData(usernames);
            } else {
                response.setStatus(404);
                response.setMsg("没有找到用户信息");
            }
        } catch (Exception e) {
            response.setStatus(500);
            response.setMsg("用户列表查询失败: " + e.getMessage());
        }
        return response;
    }
    @GetMapping("listAll")
    public ResponseBean<List<User>> listAllUsers() {
        ResponseBean<List<User>> response = new ResponseBean<>();
        try {
            List<User> users = userDAO.selectList(null);
            for( User user : users) {
                // 清除密码信息
                user.setPassword(null);
                user.setRole(null);
            }
            if (users != null && !users.isEmpty()) {
                response.setStatus(200);
                response.setMsg("用户列表查询成功");
                response.setData(users);
            } else {
                response.setStatus(404);
                response.setMsg("没有找到用户信息");
            }
        } catch (Exception e) {
            response.setStatus(500);
            response.setMsg("用户列表查询失败: " + e.getMessage());
        }
        return response;
    }


    @PostMapping("/login")
    public ResponseBean<Map<String, Object>> login(User user) throws JsonProcessingException {
        ResponseBean<User> rb = userService.getUser(user);
        ResponseBean<Map<String, Object>> tokenResponse;
        if(rb.getStatus() == 200) {
            User user1 = rb.getData();
            user1.setPassword(null);
            ObjectMapper om = new ObjectMapper();
            String userJson = om.writeValueAsString(user1);
            // 生成JWT Token
            String token = JWTTool.createToken(userJson);
            redisDAO.set(user1.getUserId().toString(), token, 60 * 30, TimeUnit.SECONDS);
            tokenResponse = new ResponseBean<>(200, "登录成功", new HashMap<>() {{
                put("token", token);
                put("user", user1);
            }});
        } else {
            tokenResponse = new ResponseBean<>(400, rb.getMsg());
        }
        return tokenResponse;
    }

    @GetMapping("/getCareTakers")
    public ResponseBean<List<User>> getCareTakers() {
        return userService.getUserByRole();
    }

    @PostMapping("/add")
    public ResponseBean<String> addUser(User user) {
        ResponseBean<String> response = new ResponseBean<>();
        try {
            if(userDAO.insert(user) > 0){
                response.setStatus(200);
                response.setMsg("用户添加成功");
                return response;
            }else {
                response.setStatus(400);
                response.setMsg("用户添加失败，可能是数据不完整或重复");
            }
        } catch (Exception e) {
            response.setStatus(500);
            response.setMsg("用户添加失败: " + e.getMessage());
        }
        return response;
    }

    @PostMapping("/update")
    public ResponseBean<String> updateUser(User user) {
        ResponseBean<String> response = new ResponseBean<>();
        try {
            if (userDAO.updateById(user) > 0) {
                response.setStatus(200);
                response.setMsg("用户更新成功");
            } else {
                response.setStatus(404);
                response.setMsg("用户未找到或未做任何更改");
            }
        } catch (Exception e) {
            response.setStatus(500);
            response.setMsg("用户更新失败: " + e.getMessage());
        }
        return response;
    }

    @GetMapping("/pageCaretakers")
    public PageResponseBean<List<User>> pageCareTakers(String username, String phone,Long page, Long size) {
        return userService.pageCareTakers(username, phone, page, size);
    }

    @GetMapping("/getUser")
    public ResponseBean<User> getUser(Long userId) {
        ResponseBean<User> response = new ResponseBean<>();
        try {
            User user = userDAO.selectById(userId);
            if (user != null) {
                response.setStatus(200);
                response.setMsg("用户信息查询成功");
                response.setData(user);
            } else {
                response.setStatus(404);
                response.setMsg("用户信息不存在");
            }
        } catch (Exception e) {
            response.setStatus(500);
            response.setMsg("用户信息查询失败: " + e.getMessage());
        }
        return response;
    }

    // 管理员端 护工管理 设置服务对象 显示所有健康管家表
    // 支持根据管家名查询
    @GetMapping("/pageCaretakersByName")
    public PageResponseBean<List<User>> pageCaretakersByName(Long cur, Long number , User user) {
        return userService.pageCareTakersByName(cur, number, user);
    }
}
